<template>
  <div class="my-application-table">
    <!-- 顶部搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="search-bar" @submit.prevent>
      <el-form-item label="申请ID">
        <el-input v-model="searchForm.applicationId" placeholder="输入申请ID" clearable style="width: 140px;" />
      </el-form-item>
      <el-form-item label="申请日期">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px;"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 120px;">
          <el-option label="全部" value="" />
          <el-option 
            v-for="(label, value) in statusLabelMap" 
            :key="value" 
            :label="label" 
            :value="value" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      v-if="tableData.length > 0 || loading"
      :data="tableData"
      v-loading="loading"
      border
      style="width: 100%; border-radius: 8px; margin-top: 8px;"
      :row-class-name="rowClassName"
    >
      <el-table-column prop="applicationId" label="申请ID" width="100" />
      <el-table-column prop="userName" label="申请人" width="120" />
      <el-table-column prop="applyDate" label="申请日期" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.applyDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)" :style="statusTagStyle(scope.row.status)" class="status-tag">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="classroomType" label="教室类型" width="120">
        <template #default="scope">
          {{ getClassroomTypeLabel(scope.row.classroomType) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">查看详情</el-button>
          <el-button type="success" size="small" @click="handleViewAllocation(row)">查看分配结果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty
      v-if="!loading && tableData.length === 0"
      description="暂无申请记录"
      :image-size="120"
      class="empty-block"
    >
      <el-button type="primary" @click="newApplication">新建申请</el-button>
    </el-empty>

    <!-- 分页控件 -->
    <div class="table-pagination" v-if="total > 0">
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="onPageChange"
        @size-change="onPageSizeChange"
      />
    </div>

    <el-dialog v-model="detailDialogVisible" title="申请详情" width="500px">
      <div v-if="currentDetail">
        <p>申请ID：{{ currentDetail.applicationId }}</p>
        <p>申请人：{{ currentDetail.userName }}</p>
        <p>申请类型：{{ getApplicationTypeLabel(currentDetail.applicationType) }}</p>
        <p>教室类型：{{ getClassroomTypeLabel(currentDetail.classroomType) }}</p>
        <p>预计人数：{{ currentDetail.expectedPeople }}</p>
        <p>申请日期：{{ currentDetail.applyDate }}</p>
        <p>使用时间：{{ currentDetail.startTime }} - {{ currentDetail.endTime }}</p>
        <p>用途：{{ currentDetail.purpose }}</p>
        <p>设备需求：{{ currentDetail.equipmentNeeds }}</p>
        <p>状态：{{ getStatusLabel(currentDetail.status) }}</p>
      </div>
    </el-dialog>

    <el-dialog v-model="allocationDialogVisible" title="分配结果" width="400px">
      <div v-if="currentAllocation">
        <p>教室编号：{{ currentAllocation.classroomCode || currentAllocation.classroomName || '未分配' }}</p>
        <p>教室类型：{{ getClassroomTypeLabel(currentAllocation.classroomType) }}</p>
        <p>分配状态：{{ currentAllocation.classroomId ? '已分配' : '未分配' }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getStatusLabel, getStatusTag, statusLabelMap, getClassroomTypeLabel, getApplicationTypeLabel } from '@/utils/statusMap'
import { cancelApplication as cancelApplicationApi } from '@/api/classroom'
import dayjs from 'dayjs'

interface ApplicationItem {
  applicationId: number
  userName: string
  applicationType: string
  classroomType: string
  expectedPeople: number
  applyDate: string
  startTime: string
  endTime: string
  purpose: string
  equipmentNeeds: string
  status: string
  classroomName?: string
  classroomId?: number
  classroomCode?: string
}

const tableData = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)

const searchForm = ref({
  applicationId: '',
  dateRange: [],
  status: ''
})

// 假设有用户ID
const userId = 1

const detailDialogVisible = ref(false)
const currentDetail = ref<ApplicationItem | null>(null)
const allocationDialogVisible = ref(false)
const currentAllocation = ref<ApplicationItem | null>(null)

async function fetchData() {
  loading.value = true
  try {
    const params = {
      userId,
      keyword: searchForm.value.applicationId || undefined,
      status: searchForm.value.status || undefined,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    const res = await axios.get('/api/classroom/page', { params })
    tableData.value = res.data?.data?.list || []
    total.value = res.data?.data?.total || 0
  } catch (e) {
    ElMessage.error('获取申请列表失败')
  } finally {
    loading.value = false
  }
}

function resetSearch() {
  searchForm.value = { applicationId: '', dateRange: [], status: '' }
  pageNum.value = 1
  fetchData()
}

function onPageChange(val: number) {
  pageNum.value = val
  fetchData()
}
function onPageSizeChange(val: number) {
  pageSize.value = val
  pageNum.value = 1
  fetchData()
}

function formatDate(date: string) {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''
}

function statusTagStyle(status: string) {
  return {
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(22,93,255,0.08)',
    fontWeight: 500
  }
}
function handleViewDetail(row: any) {
  currentDetail.value = row
  detailDialogVisible.value = true
}
function handleViewAllocation(row: any) {
  currentAllocation.value = row
  allocationDialogVisible.value = true
}
function cancelApplication(row: any) {
  ElMessageBox.confirm('确定要取消该申请吗？', '提示', { type: 'warning' })
    .then(() => {
      cancelApplicationApi(row.applicationId).then(() => {
        ElMessage.success('取消成功')
        fetchData()
      }).catch(() => {
        ElMessage.error('取消失败')
      })
    })
}
function reapply(row: any) {
  ElMessage.info('重新申请功能待实现')
}
function newApplication() {
  ElMessage.info('新建申请功能待实现')
}
function rowClassName() {
  return 'my-application-row'
}

onMounted(fetchData)
</script>

<style scoped>
.my-application-table {
  background: #fff;
  border-radius: 8px;
  padding: 16px 16px 24px 16px;
}
.search-bar {
  margin-bottom: 8px;
  padding: 8px 0 0 0;
}
.status-tag {
  border-radius: 8px !important;
  box-shadow: 0 2px 8px rgba(22,93,255,0.08);
  font-weight: 500;
}
.table-pagination {
  margin-top: 16px;
  text-align: center;
}
.my-application-row:hover {
  background: #F0F2F6 !important;
}
.empty-block {
  margin: 32px 0 0 0;
}
</style> 